package priv.lirenhe.dissertation.bdb.url_queue;

import java.io.File;
import java.util.List;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import priv.lirenhe.dissertation.bdb.BdbPersistentQueue;
import priv.lirenhe.dissertation.bdb.util.ProjectPath;

public class UsedUrlQueue {
	private BdbPersistentQueue<String> usedUrlQueueVar = null;
	public UsedUrlQueue(){
		String bdbDir = null;
		String bdbName = "usedUrlQueue";
		try {
			PropertiesConfiguration propConfig = new PropertiesConfiguration();
			propConfig.setEncoding("UTF-8");
			propConfig.load("bdb.properties");
			bdbDir = (String) propConfig.getProperty("bdbDir");
			if(bdbDir == null){
				bdbDir = ProjectPath.getFolderPathInProject("bdb");
				System.out.println("UsedUrlQueue bdbDir="+bdbDir);
			}
			File file = new File(bdbDir);
			if(!file.exists()){
				file.mkdirs();
			}
			usedUrlQueueVar = new BdbPersistentQueue<String>(bdbDir, bdbName, String.class);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * getUsedUrl 获取值,从头部获取,返回值为null的话将去掉，再往后移取出不为null的值
	 * @return
	 * @throws Exception
	 */
	public String getUsedUrl() throws Exception{
		String usedUrl = null;
		synchronized (usedUrlQueueVar) {
			if(!usedUrlQueueVar.isEmpty()){
				usedUrl = usedUrlQueueVar.peek();
			}
		}
		return usedUrl;
	}
	
	/**
	 * getListOfUsedUrl 获取数据库中所有value，注意数据格式：key-value，需要使用split("-")进行字符串分割
	 * @return
	 */
	public List<String> getListOfUsedUrl(){
		List<String> listOfUsedUrl = null;
		synchronized (listOfUsedUrl) {
			if(!usedUrlQueueVar.isEmpty()){
				listOfUsedUrl = usedUrlQueueVar.getAllFromQueue();
			}
		}
		return listOfUsedUrl;
	}
	
	/**
	 * setusedUrl  插入值 
	 * @param str
	 * @return
	 */
	public boolean setusedUrl(String str){
		boolean flag = false;
		if(!usedUrlQueueVar.isContainValue(str)){
			flag = usedUrlQueueVar.offer(str);
		}
		return flag;
	}
	
	public int setusedUrlOfList(List<String> list){
		for(String usedUrl:list){
			if(!usedUrlQueueVar.isContainValue(usedUrl)){
				usedUrlQueueVar.offer(usedUrl);
			}
		}
		return list.size();
	}
	
	/**
	 * getAllFromQueue 获取数据库中所有value，注意数据格式：key-value，需要使用split("-")进行字符串分割
	 * @return
	 */
	public List<String> getAllFromQueue(){
		return usedUrlQueueVar.getAllFromQueue();
	}
	
	public boolean isContainsValue(String value){
		return usedUrlQueueVar.isContainValue(value);
	}
	
	public void closeBDB(){
		usedUrlQueueVar.close();
	}
	
	public void syncBDB(){
		usedUrlQueueVar.sync();
	}
	
	public void clear(){
		usedUrlQueueVar.clear();
	}
	
	public boolean isEmpty(){
		return usedUrlQueueVar.isEmpty();
	}
	
	public static void main(String[] args) {
		UsedUrlQueue sld = new UsedUrlQueue();
//		sld.clear();
		System.out.println(sld.isEmpty());
	}
}
